package tool

import (
	"blizzard/app/utils/token"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
	"github.com/gogf/gf/util/guid"
	"io"
	"time"
)

// 获取int类型时间戳
func GetTime() int {
	return gconv.Int(time.Now().Unix())
}

// 获取string类型时间戳
func GetTimeString() string {
	return gconv.String(time.Now().Unix())
}

// MD5加密
func Md5String(str string) string {
	return gmd5.MustEncrypt(str)
}

//生成Guid字串
func UniqueId() string {
	b := make([]byte, 48)

	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return ""
	}
	return Md5String(base64.URLEncoding.EncodeToString(b))
}


// 获取随机字符串
func RndString(l int) string {
	var str string
	str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	return grand.Str(str, l)
}

// 创建sessionId
func CreateSessionId(r *ghttp.Request) string {
	var (
		address = r.RemoteAddr
		header  = fmt.Sprintf("%v", r.Header)
	)
	return guid.S([]byte(address), []byte(header))
}

// 获取卡密时间
func GetCardType(ti int, ty int) int {
	switch ty {
	case 2:
		ti = ti * 60
	case 3:
		ti = ti * 3600
	case 4:
		ti = ti * 86400
	case 5:
		ti = ti * 604800
	case 6:
		ti = ti * 2592000
	case 7:
		ti = ti * 31536000
	default:
		ti = ti
	}
	return ti
}

func GetCard(r *ghttp.Request) string {
	return CreateSessionId(r)
}

func GetEmailCode() string {
	return grand.Digits(6)
}

func GetToken(key, name, pass string, id int) string {
	issuer := g.Cfg().GetString("AppName")
	Token, err := token.CreateToken(key, issuer, id, name, pass)
	if err != nil {
		return err.Error()
	}
	return Token
}

func GetCardToken(key string, id int) string {
	issuer := g.Cfg().GetString("AppName")
	cardToken, err := token.CreateCardToken(key, issuer, id)
	if err != nil {
		return err.Error()
	}
	return cardToken
}

func ParseToken(tokenstr, secret string) jwt.Claims {
	claims, err := token.ParseToken(tokenstr, secret)
	if err != nil {
		return nil
	}
	return claims
}